import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.regex.Matcher;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;

/**
 * This class creates and controlls the GUI functions of the search programe.
 * Such as interacting with the user and displaying results of the search.
 * 
 * @author Mitchell Whitehouse
 * @author Andrew Evans	
 * @author Duncan Grant
 * @version     1                                 
 * @since       1.6                                      
 */
public class SearchGUI extends JFrame{
	
	private JTextField query;
	private JMenuItem jMenuItemLoad;
	private JMenuItem jMenuItemExit;
	private JMenu jMenuFile;
	private MADSearch search;
	private JButton searchButton;
	private JTextPane output;
	private JPanel resultsPanel;
	private JFileChooser fc = new JFileChooser();
	private JButton createButton;

	/**
	 * Class Constructor
	 * @param s The search program used to communicate user responses
	 */
	public SearchGUI(MADSearch s)
	{
		search = s;
		setup();
	}
	/**
	 * Method builds the GUI, by creating and managing components and 
	 * layout for the program, as well as detailing action listners to 
	 * the buttons to interact with the search progmram
	 */
	public void setup()
	{
		setSize(700,500);
		setLocationRelativeTo(null);
		setTitle("MAD Search");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		
		JMenuBar mb = new JMenuBar();
		jMenuFile = new JMenu("File");
		jMenuItemLoad = new JMenuItem("Load Index");
		jMenuItemLoad.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				int returnVal = fc.showOpenDialog(SearchGUI.this);	
				if (returnVal == fc.APPROVE_OPTION) 
				{
						//Load a file chooser so the user can specify a file
			            String fileName = fc.getSelectedFile().getPath();
			            //Convert the file path into java-friendly string
			            fileName.replaceAll(Matcher.quoteReplacement("\\"), "/");
			            //Load the index
			            search.loadIndexTable(fileName);
			            output.setText("Index (" + fileName + ") loaded successfully");
				}			
			}
		});
		jMenuItemExit = new JMenuItem("Exit");
		jMenuItemExit.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				SearchGUI.this.closeGUI();
			}
		});
		jMenuFile.add(jMenuItemLoad);
		jMenuFile.add(jMenuItemExit);
		mb.add(jMenuFile);
		this.setJMenuBar(mb);
		
		resultsPanel = new JPanel();
		resultsPanel.setBackground(Color.white);
		resultsPanel.setBorder(BorderFactory.createTitledBorder("Results"));
		output = new JTextPane();
		output.setContentType("text/html");
		output.setBackground(Color.white);
		output.setSize(new Dimension(790,500));
		output.setAlignmentY(LEFT_ALIGNMENT);
		output.setAlignmentX(TOP_ALIGNMENT);
		resultsPanel.add(output);
		
		JPanel queryPanel = new JPanel();
		
		createButton = new JButton("Create Index");
		createButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				//new Thread(new MADIndexer(search.getStopWords(),SearchGUI.this)).start();
				search.IndexCrawledPages(search.getInputFileName(), search.getOutputFileName());
				
			}
		});
		searchButton = new JButton("Search");
		searchButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e)
			{
				//Process user input and search the index for the query words
				String searchTerms = query.getText();
				//Remove punctuation as this is not in the index so needs to be removed
				//Also convert to lower case
				searchTerms = searchTerms.toLowerCase().replaceAll("[^A-Za-z0-9 ]", "");
				String[] results = search.search(searchTerms);
				//Set message reminding what user searched for
				resultsPanel.setBorder(BorderFactory.createTitledBorder("Results for \"" + searchTerms+ "\" (" + results.length +" Results)"));
				//Build results string to be displayed
				String resultsString = "<html>";
				for(int x = 0; x < results.length; x++)
				{
					resultsString = resultsString + "<a href = "+ results[x] + ">" + (results[x] + "</a> <br>");
				}
				output.setText(resultsString);
			}
		});	
		queryPanel.add(createButton);
		queryPanel.add(searchButton);
		query = new JTextField(40);
		queryPanel.add(searchButton);
		queryPanel.add(query);
	
		
		mainPanel.add(queryPanel,BorderLayout.NORTH);
		mainPanel.add(new JScrollPane(resultsPanel),BorderLayout.CENTER);
		add(mainPanel);
		setVisible(true);
	}
	
	public void setText(String text)
	{
		output.setText(text);
	}
	/**
	 * Closes the GUI
	 */
	private void closeGUI()
	{
		this.dispose();
	}
}
